﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Google.Protobuf;
using GoogleSpeechDemo;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace WebApplication9.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class VoiceController : ControllerBase
    {
        private readonly ILogger<VoiceController> _logger;
        private readonly IGoogleTTSService _googleTTSService;
        private readonly IGoogleSTTService _googleSTTService;

        public VoiceController(ILogger<VoiceController> logger,
            IGoogleTTSService googleTTSService,
            IGoogleSTTService googleSTTService)
        {
            _logger = logger;
            _googleTTSService = googleTTSService;
            _googleSTTService = googleSTTService;
        }

        [HttpPost]
        [Route("stt")]
        public Task<string> STT([FromBody]STTInput input)
        {
            return _googleSTTService.SpeechToTextAsync(input.encoding, input.language, input.speech);
        }

        [HttpPost]
        [Route("tts")]
        public Task<string> TTS([FromBody]TTSInput input)
        {
            return _googleTTSService.TextToSpeechAsync(input.encoding, input.language, input.voiceGender, input.text);
        }

        [HttpPost]
        [Route("tts/mp3")]
        public ActionResult MP3([FromBody]MP3Input input)
        {
            using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(input.content)))
            {
                byte[] buff = stream.ToArray();
                return File(fileContents:buff, contentType:"audio/mpeg", fileDownloadName:"audio.mp3");
            }
        }

        [HttpPost]
        [Route("base64")]
        public string Base64([FromForm] Base64Input input)
        {
            using(var stream = input.File.OpenReadStream())
            {
                //long length = input.File.Length;
                //byte[] bytes = new byte[length];
                //stream.Read(bytes, 0, (int)length);                
                //return Convert.ToBase64String(bytes);
                return ByteString.FromStream(stream).ToBase64(); 
            }
        }
    }
}
